package com.imti.retrofitweatherdemo.logic;

import android.content.Context;
import com.imti.retrofitweatherdemo.BaseApplication;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class NewsDetailLogic
{

    private static final String TAG = NewsDetailLogic.class.getSimpleName();

    private BaseApplication application;

    private static NewsDetailLogic sInstance;

    private INewsDetailLogic iNewsLogic;

    private Context context;

    public void setiNewsLogic(INewsDetailLogic iNewsLogic)
    {
        this.iNewsLogic = iNewsLogic;
    }

    private NewsDetailLogic(BaseApplication application, Context context)
    {
        this.application = application;
        this.context = context;
    }

    public static NewsDetailLogic getInstance(BaseApplication application, Context context)
    {
        if (null == sInstance)
        {
            sInstance = new NewsDetailLogic(application, context);
        }
        return sInstance;
    }

    public void requestNewsDetail(String uniqueKey)
    {
        application.getNewsRequest().requestNewsDetail(uniqueKey)
            .map(new Func1<NewsDetailData, NewsDetail>()
            {
                @Override
                public NewsDetail call(NewsDetailData newsDetailData)
                {
                    NewsDetail detail = new NewsDetail();
                    detail.setAuthor(newsDetailData.getResult().getDetail().getAuthor_name());
                    detail.setDate(newsDetailData.getResult().getDetail().getDate());
                    detail.setTitle(newsDetailData.getResult().getDetail().getTitle());
                    detail.setUrl(newsDetailData.getResult().getDetail().getUrl());

                    detail.setContent(newsDetailData.getResult().getContent());

                    return detail;
                }
            }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<NewsDetail>()
            {
                @Override
                public void call(NewsDetail newsDetail)
                {
                    if (null != iNewsLogic)
                    {
                        iNewsLogic.requestNewsDetail(newsDetail);
                    }
                }
            });

    }
}
